#pragma once
#include "market_data_interface.h"

#ifdef _WIN32
#include "ctp/windows64/ThostFtdcMdApi.h"
#else
#include "ctp/linux64/ThostFtdcMdApi.h"
#endif

#include "spdlog/spdlog.h"

namespace hft {

class CtpMdInterface : public MarketDataInterface, public CThostFtdcMdSpi {
public:
    using DataCallback = std::function<void(const MarketData&)>;
    using LogCallback = std::function<void(const std::string&)>;
    using ErrorCallback = std::function<void(const std::string&)>;

    CtpMdInterface(const std::string& frontAddr, const std::string& brokerId, 
                  const std::string& userId, const std::string& password);
    ~CtpMdInterface();

    // MarketDataInterface 实现
    bool connect() override;
    void disconnect() override;
    bool subscribe(const std::vector<std::string>& symbols) override;
    bool unsubscribe(const std::vector<std::string>& symbols) override;
    std::string name() const override { return "CTP"; }
    void setAutoReconnect(bool enable) { m_autoReconnect = enable; }
    void setLogCallback(LogCallback callback) { m_logCallback = callback; }
    void setErrorCallback(ErrorCallback callback) { m_errorCallback = callback; }

    // CThostFtdcMdSpi 回调接口
    void OnFrontConnected() override;
    void OnFrontDisconnected(int nReason) override;
    void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, 
                       CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, 
                           CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnHeartBeatWarning(int nTimeLapse) override;
    void OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData) override;

private:
    CThostFtdcMdApi* m_api;
    std::string m_frontAddr;
    std::string m_brokerId;
    std::string m_userId;
    std::string m_password;
    bool m_connected;
    bool m_autoReconnect = false;
    int m_requestId;
    DataCallback m_dataCallback;
    LogCallback m_logCallback;
    ErrorCallback m_errorCallback;
};

} // namespace hft